from flask import Blueprint, render_template, request, redirect, flash, json, send_file,session
from models import *
from functools import wraps

blue = Blueprint("blue", __name__)

def checklogin(func):
    def inner(*args,**kwargs):
        if session.get("username"):
            return func(*args,**kwargs)
        else:
            return redirect("/login")
    return inner

@checklogin
@blue.route("/add", methods=["GET", "POST"])
def add():
    if request.method == "GET":
        return render_template("addgoods.html")
    else:
        name = request.form.get("name")
        price = request.form.get("price")
        pic = request.files.get("pic")
        print(name,price,pic)
        index = pic.filename.rfind(".")
        ret = pic.filename[index + 1:]
        if ret != "png":
            return {"msg": "添加的不是png文件"}
        pic.save("static/upload/" + pic.filename)
        goods = Goods(name=name, price=price, img="/static/upload/" + pic.filename)
        db.session.add(goods)
        db.session.commit()
        return {"msg": "添加成功"}

@blue.route("/page", methods=["GET", "POST"])
@checklogin
def page():
    pag_num = int(request.args.get("pag_num", 1))
    per_num = 2
    pagination = Goods.query.paginate(pag_num, per_num)
    return render_template("page.html", pages=pagination)

@checklogin
@blue.route("/download/<int:id>")
def download(id):
    goods = Goods.query.get(id)
    goodslist = []
    dictlist = {}
    dictlist["id"] = goods.id
    dictlist["name"] = goods.name
    dictlist["price"] = goods.price
    dictlist["img"] = goods.img
    goodslist.append(dictlist)

    with open("static/" + goods.name + ".json", "w") as f:
        content = json.dumps(goodslist, ensure_ascii=False)
        f.write(content)
    goods.count += 1
    db.session.commit()
    return send_file("static/" + goods.name + ".json", as_attachment=True, cache_timeout=1)
